import { get, post } from '@/axios/http'
import { useUsers } from '@/stores'
import comFunc from '@/common/comFunc'
import { Sysinfo, ServerConfig } from '@/common/config'
import { action } from '@/common/actionHelper'

const userStore = useUsers()
/**
 *
 * @returns 获取菜单
 */
export const getMenu = async (): Promise<Array<any>> => {
  if (Sysinfo.UseStaticMenu) {
    let menulist = (await import('./menu.json')).default
    let rolemenu = (await import('./roleMenu.json')).default
    let mymenu = rolemenu.filter((w) => w.roleno === userStore.roleNo)
    let menu: any[] = []
    mymenu.forEach((item) => {
      const m = menulist.find((w) => w.function_no === item.functionno)
      if (m) {
        const t: any = {}
        Object.assign(t, m)
        t.actions = item.actions
        menu.push(t)
      }
    })
    // if (!menu.find((m) => m.function_url === '/dashboard/userinfo')) {
    //   // 用户中心为默认自带功能
    //   menu.push({
    //     "function_no": "F002",
    //     "function_name": "用户中心",
    //     "function_url": "/dashboard/userinfo",
    //     "p_function_no": "",
    //     "sort_num": 1,
    //     "target": "_blank",
    //     "url_type": "Router",
    //     "icon": "iconfont icon-yuangongguanli",
    //     "is_menu": false
    // })
    // }
    return menu
  } else {
    let rerolemenu = await getRoleAuth(userStore.roleNo)
    if (!rerolemenu.isSuccess) {
      return []
    }
    rerolemenu.data.function.forEach((item) => {
      let aitem = rerolemenu.data.functionActions.find((w) => w.function_no === item.function_no)
      if (aitem) {
        item.actions = aitem.actions
      }
    })
    return rerolemenu.data.function
  }
}
export const deleteMenu = async (
  functionno: string
): Promise<{
  isSuccess: boolean
  msg: string
}> => {
  // 逻辑待开发
  return {
    isSuccess: false,
    msg: '功能开发中'
  }
}
export const updateMenu = async (
  data: MenuDataModel
): Promise<{
  isSuccess: boolean
  msg: string
}> => {
  // 逻辑待开发
  return {
    isSuccess: false,
    msg: '功能开发中'
  }
}
export const addMenu = async (
  data: MenuDataModel
): Promise<{
  isSuccess: boolean
  msg: string
}> => {
  // 逻辑待开发
  return {
    isSuccess: false,
    msg: '功能开发中'
  }
}
declare type LoginResult = {
  isSuccess: boolean
  msg: string
}
/**
 * 登录
 * @param id
 * @param pwd
 * @returns
 */
export const doLogin = async (id: string, pwd: string): Promise<LoginResult> => {
  const data = await post('/project/login/doLogin', {
    loginName: id,
    password: comFunc.getMD5String(pwd)
  }).catch(() => {
    return null
  })
  if (!data)
    return {
      isSuccess: false,
      msg: '用户名或密码错误'
    } as LoginResult
  const success = data.data.success
  const msg = data.data.message
  if (!success) {
    return {
      isSuccess: false,
      msg: msg
    } as LoginResult
  }

  const loginInfo = data.data.data
  if (loginInfo) {
    let name = ''
    let rolename = ''
    let roleno = ''
    // 登录账号的name/username
    if (loginInfo.name) {
      name = decodeURIComponent(loginInfo.name)
    } else {
      name = '佚名'
    }
    // if (loginInfo.rolename) {
    //   rolename = decodeURIComponent(loginInfo.rolename)
    // }
    userStore.setLoginToken(loginInfo.token)
    const rolere = await getRoles()
    if (rolere.isSuccess) {
      const item = rolere.data?.find((w) => w.roleId === loginInfo.roleId)
      rolename = item?.rolename || ''
      roleno = item?.roleno
    }
    if (id === 'admin' && comFunc.nvl(roleno) === '') {
      roleno = 'admin'
      rolename = '系统管理员'
    }
    userStore.setLoginInfo({
      loginUID: comFunc.nvl(loginInfo.objectId),
      userName: name,
      userNo: comFunc.nvl(loginInfo.userno),
      userType: comFunc.nvl(loginInfo.usertype),
      userUid: comFunc.nvl(loginInfo.objectId),
      nameId: comFunc.nvl(loginInfo.objectId),
      avatar: loginInfo.imgPath ? comFunc.nvl(loginInfo.imgPath) : '',
      roleNo: roleno,
      roleName: rolename,
      siteId: comFunc.nvl(loginInfo.siteId)
    })
  }

  return {
    isSuccess: true,
    msg: '登录成功'
  }
}
export const getActionOptions = async (): Promise<{
  isSuccess: boolean
  msg: string
  data: any[]
}> => {
  let roles = (await import('./action.json')).default
  return {
    isSuccess: true,
    msg: '',
    data: roles
  }
}
export const getRoles = async (): Promise<{
  isSuccess: boolean
  msg: string
  data: any[]
}> => {
  const re = await get('/project/user/loadAllRole').catch((err) => {
    return err.response || err
  })
  if (!re)
    return {
      isSuccess: false,
      msg: '操作失败：服务端操作失败',
      data: []
    }
  if (!re.data)
    return {
      isSuccess: false,
      msg: '操作失败：服务端未返回结果',
      data: []
    }
  if (re.data.code !== 200) {
    return {
      isSuccess: false,
      msg: re.data.message,
      data: []
    }
  }
  let list: any[] = []
  re.data.data.forEach((item) => {
    list.push({
      roleId: item.objectId,
      roleno: item.roleCode,
      rolename: item.roleName
    })
  })
  return {
    isSuccess: re.data.success,
    msg: re.data.message || '操作失败: 未知错误',
    data: list
  }
}
export const updateRole = async (data: {
  roleno: String
  rolename: String
  roleId: String
}): Promise<{
  isSuccess: boolean
  msg: string
}> => {
  const re = await post('/project/user/updateRole', {
    objectId: data.roleId,
    roleCode: data.roleno,
    roleName: data.rolename
  })
  if (!re)
    return {
      isSuccess: false,
      msg: '操作失败：服务端操作失败'
    }
  if (!re.data)
    return {
      isSuccess: false,
      msg: '操作失败：服务端未返回结果'
    }
  return {
    isSuccess: re.data.success,
    msg: re.data.message
  }
}
export const addRole = async (data: {
  roleno: String
  rolename: String
}): Promise<{
  isSuccess: boolean
  msg: string
}> => {
  const re = await post('/project/user/addRole', {
    roleCode: data.roleno,
    roleName: data.rolename
  })
  if (!re)
    return {
      isSuccess: false,
      msg: '操作失败：服务端操作失败'
    }
  if (!re.data)
    return {
      isSuccess: false,
      msg: '操作失败：服务端未返回结果'
    }
  return {
    isSuccess: re.data.success,
    msg: re.data.message
  }
}
export const delRole = async (data: {
  roleno: String
  rolename: String
  roleId: String
}): Promise<{
  isSuccess: boolean
  msg: string
}> => {
  const re = await post('/project/user/deleteRoleById?objectId=' + data.roleId)
  if (!re)
    return {
      isSuccess: false,
      msg: '操作失败：服务端操作失败'
    }
  if (!re.data)
    return {
      isSuccess: false,
      msg: '操作失败：服务端未返回结果'
    }
  return {
    isSuccess: re.data.success,
    msg: re.data.message
  }
}
export const getRoleAuth = async (
  roleNo: string
): Promise<{
  isSuccess: boolean
  msg: string
  data: {
    function: any[]
    login: any[]
    functionActions: any[]
  }
}> => {
  let menulist = (await import('./menu.json')).default
  const reroles = await getRoles()
  if (!reroles.isSuccess) {
    return {
      isSuccess: false,
      msg: reroles.msg,
      data: {
        function: [],
        login: [],
        functionActions: []
      }
    }
  }
  const role = reroles.data?.find((w) => w.roleno === roleNo)
  if (!role) {
    return {
      isSuccess: false,
      msg: '未找到该角色信息',
      data: {
        function: [],
        login: [],
        functionActions: []
      }
    }
  }

  // let rolemenu = (await import('./roleMenu.json')).default
  const re = await get('/project/user/loadFuncByRoleId?roleId=' + role.roleId)
  if (!re)
    return {
      isSuccess: false,
      msg: '操作失败：服务端操作失败',
      data: {
        function: [],
        login: [],
        functionActions: []
      }
    }
  if (!re.data)
    return {
      isSuccess: false,
      msg: '操作失败：服务端未返回结果',
      data: {
        function: [],
        login: [],
        functionActions: []
      }
    }
  let rolemenu: any[] = []
  re.data.data.forEach((item) => {
    let role = reroles.data.find((w) => w.roleId === item.roleId)
    if (role) {
      rolemenu.push({
        roleno: role.roleno,
        functionno: item.funcNo,
        actions: item.funcAction
      })
    }
  })
  let mymenu = rolemenu.filter((w) => w.roleno === roleNo)
  let menu: any[] = []
  let actions: any[] = []
  mymenu.forEach((item) => {
    const m = menulist.find((w) => w.function_no === item.functionno)
    if (m) {
      menu.push(m)
      actions.push({
        function_no: item.functionno,
        actions: item.actions
      })
    }
  })
  return {
    isSuccess: true,
    msg: '',
    data: {
      function: menu,
      login: [],
      functionActions: actions
    }
  }
}
export const saveRoleAuth = async (
  list: {
    roleId: String
    roleno: String
    functionno: String
    actions: String
  }[]
): Promise<{
  isSuccess: boolean
  msg: string
}> => {
  let data: any[] = []
  list.forEach((item) => {
    data.push({
      funcAction: item.actions,
      funcNo: item.functionno,
      roleId: item.roleId
    })
  })
  const re = await post('/project/user/saveFunc', data)
  if (!re)
    return {
      isSuccess: false,
      msg: '操作失败：服务端操作失败'
    }
  if (!re.data)
    return {
      isSuccess: false,
      msg: '操作失败：服务端未返回结果'
    }
  return {
    isSuccess: re.data.success,
    msg: re.data.message
  }
}

export const getAllMenus = async (): Promise<{
  isSuccess: boolean
  msg: string
  data: any[]
}> => {
  let menulist = (await import('./menu.json')).default
  return {
    isSuccess: true,
    msg: '',
    data: menulist
  }
}

export const getUsers = async (): Promise<{
  isSuccess: boolean
  msg: string
  data: any[]
}> => {
  // let menulist = (await import('./users.json')).default
  let re = await queryUsersBy({
    pageSize: 10000,
    to: 1
  })
  if (re.isSuccess) {
    return {
      isSuccess: true,
      msg: '',
      data: re.data ? re.data : []
    }
  } else {
    return {
      isSuccess: re.isSuccess,
      msg: re.msg,
      data: []
    }
  }
}

export const queryUsersBy = async (p: {
  categoryId?: string
  name?: string
  pageSize?: number
  to?: number
}): Promise<{
  isSuccess: boolean
  msg: string
  data?: any[]
  pageSize?: number
  pageNum?: number
  totalRow?: number
  totalPages?: number
}> => {
  if (!p.pageSize) p.pageSize = Sysinfo.PageSize
  if (!p.to) p.to = 1
  const re = await post('/project/user/queryAllBackUser', {
    name: comFunc.nvl(p.name) === '' ? null : p.name,
    pageNum: p.to,
    pageSize: p.pageSize
  }).catch((err) => {
    return err.response || err
  })
  const data =
    re.data && re.data.data
      ? re.data.data
      : {
          list: [],
          pageSize: Sysinfo.PageSize,
          pageNum: 1,
          totalRow: 0,
          totalPages: 0
        }
  if (re.data) {
    if (re.data.success) {
      const list = [] as any[]
      data.list?.forEach((item) => {
        const info = {
          uid: item.objectId,
          loginid: item.loginName,
          loginname: item.name,
          userno: '',
          usertype: 'System',
          loginpass: '',
          mobile: item.phone,
          qq: '',
          avatar: item.imgPath,
          roles: item.role ? item.role.split(',') : []
        }
        list.push(info)
      })
      return {
        isSuccess: re.data.success,
        msg: re.data.message,
        data: list,
        pageSize: data.pageSize > 0 ? data.pageSize : Sysinfo.PageSize,
        pageNum: data.pageNum,
        totalRow: data.total,
        totalPages: data.pages
      }
    } else {
      return {
        isSuccess: re.data.success,
        msg: re.data.message
      }
    }
  } else {
    return {
      isSuccess: false,
      msg: `查询失败:无返回结果`
    }
  }
}
export const deleteUser = async (
  data: UserModel
): Promise<{
  isSuccess: boolean
  msg: string
}> => {
  const re = await post('/project/user/deleteBackUser?objectId=' + data.uid).catch(
    (err) => err.response || err
  )
  if (!re)
    return {
      isSuccess: false,
      msg: '操作失败：服务端操作失败'
    }
  if (!re.data)
    return {
      isSuccess: false,
      msg: '操作失败：服务端未返回结果'
    }
  return {
    isSuccess: re.data.success,
    msg: re.data.message || '操作失败: 未知错误'
  }
}
export const updateUser = async (
  data: UserModel
): Promise<{
  isSuccess: boolean
  msg: string
}> => {
  let postdata = {
    imgPath: data.avatar,
    loginName: data.loginid,
    name: data.loginname,
    objectId: data.uid,
    openId: '',
    phone: data.mobile,
    role: data.roles ? data.roles[0] : '',
    roleId: data.roleId ? data.roleId[0] : ''
  }
  if (data.loginpass !== '' && data.loginpass !== '******') {
    postdata['password'] = comFunc.getMD5String(data.loginpass)
  }
  const re = await post('/project/user/updateBackUser', postdata).catch(
    (err) => err.response || err
  )
  if (!re)
    return {
      isSuccess: false,
      msg: '操作失败：服务端操作失败'
    }
  if (!re.data)
    return {
      isSuccess: false,
      msg: '操作失败：服务端未返回结果'
    }
  return {
    isSuccess: re.data.success,
    msg: re.data.message || '操作失败: 未知错误'
  }
}
export const createUser = async (
  data: UserModel
): Promise<{
  isSuccess: boolean
  msg: string
}> => {
  const re = await post('/project/user/createUser', {
    imgPath: data.avatar,
    loginName: data.loginid,
    password: comFunc.getMD5String(data.loginpass),
    name: data.loginname,
    objectId: data.uid,
    openId: '',
    phone: data.mobile,
    role: data.roles ? data.roles[0] : '',
    roleId: data.roleId ? data.roleId[0] : ''
  }).catch((err) => err.response || err)
  if (!re)
    return {
      isSuccess: false,
      msg: '操作失败：服务端操作失败'
    }
  if (!re.data)
    return {
      isSuccess: false,
      msg: '操作失败：服务端未返回结果'
    }
  return {
    isSuccess: re.data.success,
    msg: re.data.message || '操作失败: 未知错误'
  }
}
export const updateLogin2Role = async (
  loginUID: string,
  roleno: string
): Promise<{
  isSuccess: boolean
  msg: string
}> => {
  return {
    isSuccess: false,
    msg: '功能开发中'
  }
}
